package utils

import (
	"encoding/json"
	pb "gitee.com/micro-services/protocol/user/server"
	"math/rand"
	"reflect"
	"time"
)

// 时间种子随机数
func RandNum() int64 {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))

	return r.Int63n(200)
}

func StructToMap(obj interface{}) map[string]interface{} {
	t := reflect.TypeOf(obj)
	v := reflect.ValueOf(obj)

	var key = make(map[string]interface{})
	for i := 0; i < t.NumField(); i++ {
		key[t.Field(i).Name] = v.Field(i).Interface()
	}
	return key
}

func StructJsonToMap(obj *pb.ResolveToken) map[string]interface{} {
	b, _ := json.Marshal(obj)

	key := make(map[string]interface{})

	err := json.Unmarshal(b, &key)
	if err != nil {
		return nil
	}

	return key

}

func MapJsonToStruct(claims map[string]interface{}) (*pb.ResolveToken, error) {
	b, err := json.Marshal(claims)
	if err != nil {
		return nil, err
	}

	key := &pb.ResolveToken{}
	err = json.Unmarshal(b, key)
	if err != nil {
		return nil, err
	}

	return key, nil
}
